class Solution
{
public:
    long long maximumSubarraySum(vector<int> &nums, int k)
    {
        unordered_map<int, int> kElements;
        long long kSum = 0;
        for (int i = 0; i < k; ++i)
        {
            kSum += nums[i];
            ++kElements[nums[i]];
        }

        int n = nums.size();
        long long result = 0;
        if (kElements.size() == k)
        {
            result = kSum;
        }

        for (int i = k; i < n; ++i)
        {
            int prevK = nums[i - k];
            kSum -= prevK;
            kSum += nums[i];
            --kElements[prevK];
            if (kElements[prevK] == 0)
            {
                kElements.erase(prevK);
            }
            ++kElements[nums[i]];
            if (kElements.size() == k)
            {
                result = max(result, kSum);
            }
        }
        return result;
    }
};